package com.z.sys.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.z.common.aop.annotation.Log;
import com.z.common.aop.enums.BusinessType;
import com.z.common.configure.proprety.TemplateProperty;
import com.z.sys.entity.SysLog;
import com.z.sys.service.SysLogService;
import com.z.common.utils.ExcelUtil;
import com.z.common.web.base.BaseController;
import com.z.common.web.vo.request.PageVo;
import com.z.common.web.vo.response.Result;
import com.z.sys.entity.Dept;
import com.z.sys.entity.User;
import com.z.sys.service.IDeptService;
import com.z.sys.service.IUserService;
import com.z.sys.vo.UserExcelVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 员工管理Controller
 *
 * @author z
 * @date 2022-11-07
 */
@Slf4j
@RestController
@RequestMapping("/system/user")
@Api(tags = "人员管理")
public class UserController extends BaseController {

    private String prefix = "system/user";
    @Resource
    private TemplateProperty uploadProperty;

    @Autowired
    private IUserService userService;
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private IDeptService deptService;


    @GetMapping("/person")
    public ModelAndView person() {
        return jumpPage(prefix + "/person");
    }

    @GetMapping("/profile")
    public ModelAndView profile() {
        return jumpPage(prefix + "/profile");
    }

    @GetMapping("/main")
    public ModelAndView main() {
        return jumpPage(prefix + "/main");
    }

    /**
     * 查询员工管理列表
     */
    @ResponseBody
    @GetMapping("/data")
    public Result list(@ModelAttribute User user, PageVo pageVo) {
        PageInfo<User> pageInfo = userService.selectUserPage(user, pageVo, "");
        return Result.table(pageInfo);
    }
    /**
     * 按模块查询员工管理列表
     */
    @ResponseBody
    @GetMapping("/{m}/data")
    public Result list(@ModelAttribute User user, PageVo pageVo, @PathVariable("m") String m) {
        PageInfo<User> pageInfo = userService.selectUserPage(user, pageVo, m);
        return Result.table(pageInfo);
    }
    /**
     * 按条件下载人员信息
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public void export(@ModelAttribute User user, HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> list = userService.selectUserList(user, "");
        List<UserExcelVo> userList = new ArrayList<>();
        list.forEach(data ->{
            UserExcelVo temp = new UserExcelVo();
            BeanUtils.copyProperties(data, temp);
            temp.setSex(user.getSex()==0?"男":"女");
            userList.add(temp);
        });
        ExcelUtil.write(response, "UserInfo",UserExcelVo.class, userList);
    }
    /**
     * 新增员工管理
     */
    @GetMapping("/add")
    public ModelAndView add() {
        return jumpPage(prefix + "/add");
    }

    /**
     * 新增员工管理
     */
    @ResponseBody
    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        return Result.decide(userService.save(user));
    }

    /**
     * 修改员工管理
     */
    @GetMapping("/edit")
    public ModelAndView edit(Long id, ModelMap map) {
        User user =userService.getById(id);
        map.put("user", user);
        return jumpPage(prefix + "/edit");
    }

    /**
     * 修改员工管理
     */
    @ResponseBody
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        return Result.decide(userService.updateById(user));
    }

    /**
     * 删除员工管理
     */
    @ResponseBody
    @DeleteMapping("/batchRemove")
    public Result batchRemove(String ids) {
        return Result.decide(userService.removeByIds(Arrays.asList(ids.split(","))));
    }

    /**
     * 删除员工管理
     */
    @ResponseBody
    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable("id") Long id) {
        return Result.decide(userService.removeById(id));
    }

    /**
     * Describe: 根据 userId 开启\禁用用户
     * Param: SysUser
     * Return: 执行结果
     */
    @PutMapping("enable")
    @ApiOperation(value = "开启/禁用 用户")
    public Result enable(@RequestBody User user) {
        return Result.decide(userService.updateEnableById(user));
    }


    /**
     * 导入员工管理
     */
    @GetMapping("/import")
    public ModelAndView importPage() {
        return jumpPage(prefix + "/import");
    }

    /**
     * 导入user
     * @param file
     * @return
     */
    @PostMapping("upload")
    @ResponseBody
    @Log(title = "用户管理", describe = "导入用户", type = BusinessType.ADD)
    public Result upload(MultipartFile file)  {
        try {
            List<User> userList = new ArrayList<>();
            List<Dept> deptDBList = deptService.list(new QueryWrapper<Dept>().select("id,code").eq("del", 0).eq("status", "1"));
            Map<String, Dept> codeDeptMap = new HashMap<>();
            for(Dept dept: deptDBList){
                codeDeptMap.put(dept.getCode(), dept);
            }
             EasyExcel.read(file.getInputStream(), UserExcelVo.class, new AnalysisEventListener<UserExcelVo>() {
                @Override
                public void invoke(UserExcelVo data, AnalysisContext analysisContext) {
                    User user = new User();
                    BeanUtils.copyProperties(data, user);
                    user.setSex("女".equals(data.getSex())?1:0);
                    user.setPassword(new BCryptPasswordEncoder().encode("1111"));
                    user.setDeptId(codeDeptMap.get(data.getCode()).getId());
                    userList.add(user);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                    log.debug("读取完成");
                }
            }).sheet().doRead();
            userService.saveBatch(userList, 5000);
        } catch (IOException e) {
            e.printStackTrace();
            sysLogService.save(new SysLog("用户管理","导入失败，"+e.getMessage(), BusinessType.ADD));
            return Result.error("异常：" + e.getMessage());
        }
        return Result.success();
    }

    /**
     * 下载人员导入模板
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ExcelUtil.write(response, "userImport", UserExcelVo.class, null);

    }
    /**
     * 上传照片
     * @param file
     * @return
     */
/*    @PostMapping("uploadImg")
    public Result uploadImg(@RequestParam("file") MultipartFile file) {
        String result = userService.upload(file);
        if (Strings.isNotBlank(result)) {
            return Result.success(result);
        } else {
            return Result.error("上传失败");
        }
    }*/

    /**
     * 上传照片
     * @param user
     * @return
     */
    @PostMapping("uploadImg")
    public Result uploadImg(@RequestBody User user) {
        String fileId = userService.uploadHeadImg(user.getId() + "", user.getHeadImgUrl());
        if (Strings.isNotBlank(fileId)) {
            return Result.success(1, fileId);
        } else {
            return Result.error("上传失败");
        }
    }
}
